import os
import speech_recognition as sr
from pydub import AudioSegment
import logging
from typing import Optional, Tuple

logger = logging.getLogger(__name__)

class SpeechToTextService:
    """语音转文字服务"""
    
    def __init__(self):
        self.recognizer = sr.Recognizer()
        
    def convert_voice_to_text(self, file_path: str, language: str = "zh-CN") -> Tuple[bool, str]:
        """
        将语音文件转换为文字
        
        Args:
            file_path: 语音文件路径
            language: 语言代码，默认中文
            
        Returns:
            Tuple[bool, str]: (是否成功，文字内容或错误信息)
        """
        if not os.path.exists(file_path):
            return False, f"文件不存在: {file_path}"
            
        try:
            # 处理不同格式的音频文件
            audio_file = self._prepare_audio_file(file_path)
            if not audio_file:
                return False, f"不支持的音频格式: {file_path}"
                
            # 使用Google Speech Recognition API进行识别
            with sr.AudioFile(audio_file) as source:
                audio_data = self.recognizer.record(source)
                text = self.recognizer.recognize_google(audio_data, language=language)
                return True, text
                
        except sr.UnknownValueError:
            return False, "无法识别语音内容"
        except sr.RequestError as e:
            return False, f"语音识别服务请求失败: {str(e)}"
        except Exception as e:
            logger.error(f"语音转文字失败: {str(e)}")
            return False, f"处理失败: {str(e)}"
    
    def _prepare_audio_file(self, file_path: str) -> Optional[str]:
        """
        准备音频文件，转换为支持的格式
        
        Args:
            file_path: 原始音频文件路径
            
        Returns:
            Optional[str]: 处理后的音频文件路径，如果失败则返回None
        """
        file_ext = os.path.splitext(file_path)[1].lower()
        
        # 如果已经是WAV格式且适合识别，直接返回
        if file_ext == '.wav':
            return file_path
            
        try:
            # 需要转换的音频格式
            if file_ext in ['.mp3', '.amr', '.silk', '.slk', '.m4a', '.ogg']:
                # 生成临时WAV文件路径
                temp_wav_path = file_path + '.wav'
                
                # 使用pydub转换为WAV格式
                audio = AudioSegment.from_file(file_path)
                audio.export(temp_wav_path, format="wav")
                
                return temp_wav_path
            else:
                logger.warning(f"不支持的音频格式: {file_ext}")
                return None
                
        except Exception as e:
            logger.error(f"音频文件转换失败: {str(e)}")
            return None 